package server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;

import java.util.concurrent.ConcurrentMap;


/**
 * netty 服务器
 */
public class NettyServer {

    public static void main(String[] args) throws InterruptedException {
        new Thread(new Runnable() {
            @Override
            public void run() {
                runServer();
            }
        }).start();


        while (true) {
            Thread.sleep(3000);
            ConcurrentMap<String, Channel> channels = ServerHandler.channels;
            channels.forEach((k, v) -> {
                ServerHandler.sendMsg(v.id().asLongText(), "心跳检测...");
            });

        }
    }


    public static void runServer() {
        try {
            System.out.println("服务器端启动...");
            // 1.创建两个线程池,一个负责接收客户端，一个进行传输
            NioEventLoopGroup pGroup = new NioEventLoopGroup();
            NioEventLoopGroup cGroup = new NioEventLoopGroup();
            // 2.创建辅助类.ServerBootstrap 和 Bootstrap都继承自AbstractBootstrap功能都是作为入口,构建服务端和客户端
            ServerBootstrap b = new ServerBootstrap();
            // 3.创建通道（NioServerSocketChannel ），并设置socket的标准参数
            // https://www.cnblogs.com/xiaoyongsz/p/6133266.html?utm_source=itdadao&utm_medium=referral
            b.group(pGroup, cGroup).channel(NioServerSocketChannel.class)
                    // 3.1、设置缓冲区与发送区大小标识用于临时存放已完成三次握手的请求的队列的最大长度。未设置或所设置的值小于1，则使用默认值50。
                    .option(ChannelOption.SO_BACKLOG, 1024)
                    // 3.2、定义接收或者传输的系统缓冲区buf的大小
                    .option(ChannelOption.SO_SNDBUF, 32 * 1024)
                    .option(ChannelOption.SO_RCVBUF, 32 * 1024)
                    // 监听事件
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel sc) {
                            // 设置为 string 类型
                            sc.pipeline().addLast(new StringDecoder());
                            // 使用自定义类 ServerHandler 继承 ChannelHandlerAdapter 来监听
                            sc.pipeline().addLast(new ServerHandler());
                        }
                    });
            // 启动
            ChannelFuture cf = b.bind(8080).sync();
            // 关闭
            cf.channel().closeFuture().sync();
            pGroup.shutdownGracefully();
            cGroup.shutdownGracefully();
        } catch (Exception e) {
            // TODO: handle exception
        }
    }
}

